//
//  UIViewController+Helper.swift
//  CustomPresent
//
//  Created by dyoung on 2022/2/8.
//

import Foundation
import UIKit

extension UIViewController {
    
    static var current: UIViewController? {
        //获取到normal window
        guard var window = UIApplication.shared.keyWindow else {
            return nil
        }
        if window.windowLevel != UIWindow.Level.normal{
            let windows = UIApplication.shared.windows
            for item in windows{
                if item.windowLevel == UIWindow.Level.normal {
                    window = item
                    break
                }
            }
        }
        //获取window的rootVC
        var rootVc:UIViewController?
        if let frontview = window.subviews.last, let nextResponder = frontview.next {
            if nextResponder.isKind(of: UIViewController.self){
                rootVc = nextResponder as? UIViewController
            }
        }
        if rootVc == nil{
            rootVc = window.rootViewController
        }
        
        
        var next:UIViewController? = rootVc
        while next != nil {
            if next!.isKind(of: UINavigationController.self){
                next = (next as! UINavigationController).visibleViewController
            }else if next!.isKind(of: UITabBarController.self){
                next = (next as! UITabBarController).selectedViewController
            }else if next?.presentedViewController != nil{
                next = next?.presentedViewController
            }else{
                return next
            }
        }
        return nil
    }
}
